package com.ccrfid.rmc6.resource.auth;

import com.ccrfid.rmc6.appconfig.auth.Secured;
import com.ccrfid.rmc6.appconfig.exception.pojo.AppException;
import com.ccrfid.rmc6.pojo.Constants;
import com.ccrfid.rmc6.pojo.dto.JitVerifyDto;
import com.ccrfid.rmc6.resource.auth.pojo.JwtToken;
import com.ccrfid.rmc6.service.auth.AuthenticationService;
import com.ccrfid.rmc6.service.jit.JitVerifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.SecurityContext;

@Path("auth")
@Produces(MediaType.APPLICATION_JSON)
public class AuthenticationResource {
    @Autowired
    private AuthenticationService authenticationService;

    @Autowired
    private JitVerifyService jitVerifyService;

    @Context
    private HttpServletRequest httpServletRequest;

    @POST
    @Path("sign-in")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public JwtToken signin(@FormParam("username") String userAccount, @FormParam("password") String password)
            throws AppException {

        //验证用户名/密码是否匹配
        authenticationService.authenticate(userAccount, password);
        //验证IP是否匹配
        authenticationService.issueIp(userAccount, httpServletRequest);
        //发布令牌
        String token = authenticationService.issueToken(userAccount);

        return new JwtToken(Constants.authType, token);
    }

    @Secured
    @GET
    @Path("token")
    public String getToken(@Context SecurityContext securityContext) {
        System.out.println("AuthenticationScheme:" + securityContext.getAuthenticationScheme());
        System.out.println("userAccount:" + securityContext.getUserPrincipal().getName());

        return "\"test token\"";
    }

    //长春登录K宝加密需求，获取随机码
    @GET
    @Path("randomNum")
    public String getRandomNum(){
        return jitVerifyService.getRandom();
    }

    //长春登录K宝加密需求，验证证书
    @POST
    @Path("jit-verify")
    public boolean jitVerify(JitVerifyDto jitVerifyDto){

        return jitVerifyService.jitVerify(jitVerifyDto, httpServletRequest);
    }
}
